﻿// This software is the confidential and proprietary information of NetBay.
// Such confidential information should not be disclosed.
// NetBay copyright(c) 2012

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using GalaSoft.MvvmLight.Messaging;
using NetBay.Core.BusinessEntities.Historic;
using Rio.Applications.Web.Services;
using Rio.Framework.Localisation;
using Rio.Framework.Pages.AppCode.ApplicationNavigation;
using Rio.Framework.Pages.AppCode.Enums;
using Rio.Framework.Pages.Context;
using Telerik.Windows;
using Telerik.Windows.Controls.GridView;

namespace Rio.Framework.Pages.Controls.Historic
{
    public partial class HistoricDashboard : UserControl, INotifyPropertyChanged
    {
        #region Events

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        #region Fields

        private AppDisplayMode _displayMode;
        private HistoricInformation _selectedLastConsultations;
        private HistoricInformation _selectedLastIndexations;
        private HistoricInformation _selectedLastSearches;
        private HistoricInformation _selectedSavedSearches;

        #endregion

        #region Properties

        public ObservableCollection<HistoricInformation> LastConsultations { get; set; }
        public ObservableCollection<HistoricInformation> LastSearches { get; set; }
        public ObservableCollection<HistoricInformation> SavedSearches { get; set; }
        public ObservableCollection<HistoricInformation> LastIndexations { get; set; }

        public HistoricInformation SelectedLastConsultations
        {
            get { return _selectedLastConsultations; }
            set
            {
                _selectedLastConsultations = value;
                OnPropertyChanged("SelectedLastConsultations");

                LastConsultationsDisplayButton.IsEnabled = SelectedLastConsultations != null;
            }
        }

        public HistoricInformation SelectedLastSearches
        {
            get { return _selectedLastSearches; }
            set
            {
                _selectedLastSearches = value;
                OnPropertyChanged("SelectedLastSearches");

                LastSearchesDisplayButton.IsEnabled = SelectedLastSearches != null;
            }
        }

        public HistoricInformation SelectedLastIndexations
        {
            get { return _selectedLastIndexations; }
            set
            {
                _selectedLastIndexations = value;
                OnPropertyChanged("SelectedLastIndexations");

                LastIndexationsDisplayButton.IsEnabled = SelectedLastIndexations != null;
            }
        }

        public HistoricInformation SelectedSavedSearches
        {
            get { return _selectedSavedSearches; }
            set
            {
                _selectedSavedSearches = value;
                OnPropertyChanged("SelectedSavedSearches");

                SavedSearchesDeleteButton.IsEnabled = SelectedSavedSearches != null;
                SavedSearchesDisplayButton.IsEnabled = SelectedSavedSearches != null;
            }
        }

        public int HistoricMaxCountResultsDisplay { get; set; }

        public AppDisplayMode DisplayMode
        {
            get { return _displayMode; }
            set
            {
                _displayMode = value;

                switch (DisplayMode)
                {
                    case AppDisplayMode.Import:
                        LastConsultationsRadGridView.Visibility = Visibility.Collapsed;
                        SavedSearchesRadGridView.Visibility = Visibility.Collapsed;
                        LastSearchesRadGridView.Visibility = Visibility.Collapsed;
                        break;
                    case AppDisplayMode.Search:
                        LastIndexationsRadGridView.Visibility = Visibility.Collapsed;
                        break;
                }
            }
        }

        public bool IsLoaded { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        ///   Initializes a new instance of the <see cref = "SearchHistoric" /> class.
        /// </summary>
        public HistoricDashboard()
        {
            InitializeComponent();

            InitLabels();

            LastConsultationsRadGridView.AddHandler(GridViewCellBase.CellDoubleClickEvent,
                                                    new EventHandler<RadRoutedEventArgs>(OnCellDoubleClick_Consultation),
                                                    true);
            LastSearchesRadGridView.AddHandler(GridViewCellBase.CellDoubleClickEvent,
                                               new EventHandler<RadRoutedEventArgs>(OnCellDoubleClick_Search),
                                               true);
            SavedSearchesRadGridView.AddHandler(GridViewCellBase.CellDoubleClickEvent,
                                                new EventHandler<RadRoutedEventArgs>(OnCellDoubleClick_SavedSearch),
                                                true);
            LastIndexationsRadGridView.AddHandler(GridViewCellBase.CellDoubleClickEvent,
                                                  new EventHandler<RadRoutedEventArgs>(OnCellDoubleClick_Import),
                                                  true);
        }

        #endregion

        public void LoadHistoric()
        {
            if (HistoricMaxCountResultsDisplay > 0)
            {
                LoadSearchHistoric();
                LoadLastIndexations();
            }
            else
            {
                SettingsDomainContext settingsDomainContext = new SettingsDomainContext();
                settingsDomainContext.GetHistoricMaxCountResultsDisplay(
                    delegate(InvokeOperation<int> retr)
                    {
                        HistoricMaxCountResultsDisplay = retr.Value;

                        LoadSearchHistoric();
                        LoadLastIndexations();
                    },
                    null);
            }
        }

        /// <summary>
        ///   Loads the historic.
        /// </summary>
        private void LoadSearchHistoric(NotificationMessage n = null)
        {
            LoadLastConsultations();
            LoadLastSearches();
            LoadSavedSearches();
        }

        /// <summary>
        ///   Loads the last consultations.
        /// </summary>
        private void LoadLastConsultations()
        {
            LastConsultationsRadGridView.IsBusy = true;

            BusinessEntitiesDomainContext businessEntitiesDomainContext = new BusinessEntitiesDomainContext();

            var query = businessEntitiesDomainContext.GetLastConsultationsQuery(
                Constant.UserActions.CONSULTATION_DOSSIER.szGetDescription(),
                GlobalWebContext.CurrentUser.UserId,
                HistoricMaxCountResultsDisplay,
                false);

            businessEntitiesDomainContext.Load(
                query,
                delegate(LoadOperation<HistoricInformation> retr)
                    {
                        if (retr.Error == null
                            && retr.Entities != null)
                        {
                            LastConsultations = new ObservableCollection<HistoricInformation>(
                                retr.Entities
                                    .OrderByDescending(item => item.ActionDate)
                                    .ThenByDescending(item => item.ActionTime));

                            OnPropertyChanged("LastConsultations");

                            IsLoaded = true;
                        }

                        LastConsultationsRadGridView.IsBusy = false;
                    },
                null);
        }

        /// <summary>
        ///   Loads the last searches.
        /// </summary>
        private void LoadLastSearches()
        {
            LastSearchesRadGridView.IsBusy = true;

            BusinessEntitiesDomainContext businessEntitiesDomainContext = new BusinessEntitiesDomainContext();

            //Get Last Searches
            var query = businessEntitiesDomainContext.GetLastConsultationsQuery(
                Constant.UserActions.RECHERCHE.szGetDescription(),
                GlobalWebContext.CurrentUser.UserId,
                HistoricMaxCountResultsDisplay,
                false);

            businessEntitiesDomainContext.Load(
                query,
                delegate(LoadOperation<HistoricInformation> retr)
                    {
                        if (retr.Error == null
                            && retr.Entities != null)
                        {
                            LastSearches = new ObservableCollection<HistoricInformation>(
                                retr.Entities
                                    .OrderByDescending(item => item.ActionDate)
                                    .ThenByDescending(item => item.ActionTime));

                            OnPropertyChanged("LastSearches");

                            IsLoaded = true;
                        }

                        LastSearchesRadGridView.IsBusy = false;
                    },
                null);
        }

        /// <summary>
        ///   Loads the saved searches.
        /// </summary>
        private void LoadSavedSearches()
        {
            SavedSearchesRadGridView.IsBusy = true;

            //Get Saved Searches
            BusinessEntitiesDomainContext businessEntitiesDomainContext = new BusinessEntitiesDomainContext();
            var query = businessEntitiesDomainContext.GetLastConsultationsQuery(
                Constant.UserActions.RECHERCHE.szGetDescription(),
                GlobalWebContext.CurrentUser.UserId,
                HistoricMaxCountResultsDisplay,
                true);

            businessEntitiesDomainContext.Load(
                query,
                delegate(LoadOperation<HistoricInformation> retr)
                    {
                        if (retr.Error == null
                            && retr.Entities != null)
                        {
                            SavedSearches = new ObservableCollection<HistoricInformation>(
                                retr.Entities
                                    .OrderByDescending(item => item.ActionDate)
                                    .ThenByDescending(item => item.ActionTime));

                            OnPropertyChanged("SavedSearches");

                            IsLoaded = true;
                        }

                        SavedSearchesRadGridView.IsBusy = false;
                    },
                null);
        }

        /// <summary>
        ///   Loads the last indexations.
        /// </summary>
        /// <param name = "n">The n.</param>
        private void LoadLastIndexations(NotificationMessage n = null)
        {
            LastIndexationsRadGridView.IsBusy = true;

            BusinessEntitiesDomainContext businessEntitiesDomainContext = new BusinessEntitiesDomainContext();
            var query = businessEntitiesDomainContext.GetLastConsultationsQuery(
                Constant.UserActions.AJOUT_DOCUMENTS_DOSSIER.szGetDescription(),
                GlobalWebContext.CurrentUser.UserId,
                HistoricMaxCountResultsDisplay,
                false);

            businessEntitiesDomainContext.Load(
                query,
                delegate(LoadOperation<HistoricInformation> retr)
                    {
                        if (retr.Error == null
                            && retr.Entities != null)
                        {
                            LastIndexations = new ObservableCollection<HistoricInformation>(
                                retr.Entities
                                    .OrderByDescending(item => item.ActionDate)
                                    .ThenByDescending(item => item.ActionTime));

                            OnPropertyChanged("LastIndexations");

                            IsLoaded = true;
                        }

                        LastIndexationsRadGridView.IsBusy = false;
                    },
                null);
        }

        /// <summary>
        ///   Deletes the selected savd search.
        /// </summary>
        private void DeleteSelectedSavedSearch()
        {
            if (SavedSearchesRadGridView.SelectedItems != null)
            {
                List<HistoricInformation> selectedSavedSearches =
                    new List<HistoricInformation>(SavedSearchesRadGridView.SelectedItems.Cast<HistoricInformation>());
                BusinessEntitiesDomainContext businessEntitiesDomainContext = new BusinessEntitiesDomainContext();
                foreach (HistoricInformation SelectedSavedSearchesItem in selectedSavedSearches)
                {
                    businessEntitiesDomainContext.DeleteHistoricSearcSave(SelectedSavedSearchesItem.Identifier);
                    SavedSearches.Remove(SelectedSavedSearchesItem);
                }
            }
        }

        /// <summary>
        ///   Inits the labels.
        /// </summary>
        private void InitLabels()
        {
            LastIndexationsTabItem.Header = Resx.GetLabel(ResxHistoric.HISTORIC_LAST_INDEXATIONS);
            LastIndexationsDisplayButton.Content = Resx.GetLabel(ResxHistoric.HISTORIC_DISPLAY);
            LastIndexationsRadGridView.Columns["LastIndexationsDateHeader"].Header =
                Resx.GetLabel(ResxHistoric.HISTORIC_DATE_HEADER);
            LastIndexationsRadGridView.Columns["LastIndexationsHourHeader"].Header =
                Resx.GetLabel(ResxHistoric.HISTORIC_HOUR_HEADER);
            LastIndexationsRadGridView.Columns["LastIndexationsOrganizationHeader"].Header =
                Resx.GetLabel(ResxHistoric.HISTORIC_ORGANIZATION_HEADER);
            LastIndexationsRadGridView.Columns["LastIndexationsFolderTypeHeader"].Header =
                Resx.GetLabel(ResxHistoric.HISTORIC_FOLDERTYPE_HEADER);
            LastIndexationsRadGridView.Columns["LastIndexationsNbIndexedDocsHeader"].Header =
                Resx.GetLabel(ResxHistoric.HISTORIC_NBINDEXEDDOCS_HEADER);
            LastIndexationsRadGridView.Columns["LastIndexationsItemHeader"].Header =
                Resx.GetLabel(ResxHistoric.HISTORIC_ITEM_HEADER);
            LastIndexationsRadGridView.Columns["LastIndexationsIndexHeader"].Header =
                Resx.GetLabel(ResxHistoric.HISTORIC_INDEX_HEADER);

            LastConsultationsTabItem.Header = Resx.GetLabel(
                ResxHistoric.HISTORIC_LAST_CONSULTATIONS);
            LastConsultationsDisplayButton.Content = Resx.GetLabel(ResxHistoric.HISTORIC_DISPLAY);
            LastConsultationsRadGridView.Columns["LastConsultationsDateHeader"].Header =
                Resx.GetLabel(ResxHistoric.HISTORIC_DATE_HEADER);
            LastConsultationsRadGridView.Columns["LastConsultationsHourHeader"].Header =
                Resx.GetLabel(ResxHistoric.HISTORIC_HOUR_HEADER);
            LastConsultationsRadGridView.Columns["LastConsultationsOrganizationHeader"].Header =
                Resx.GetLabel(ResxHistoric.HISTORIC_ORGANIZATION_HEADER);
            LastConsultationsRadGridView.Columns["LastConsultationsFolderTypeHeader"].Header =
                Resx.GetLabel(ResxHistoric.HISTORIC_FOLDERTYPE_HEADER);
            LastConsultationsRadGridView.Columns["LastConsultationsNbDocsHeader"].Header =
                Resx.GetLabel(ResxHistoric.HISTORIC_NBDOCS_HEADER);
            LastConsultationsRadGridView.Columns["LastConsultationsIndexHeader"].Header =
                Resx.GetLabel(ResxHistoric.HISTORIC_INDEX_HEADER);

            LastSearchesTabItem.Header = Resx.GetLabel(ResxHistoric.HISTORIC_LAST_SEARCHES);
            LastSearchesDisplayButton.Content = Resx.GetLabel(ResxHistoric.HISTORIC_DISPLAY);
            LastSearchesRadGridView.Columns["LastSearchesDateHeader"].Header = Resx.GetLabel(ResxHistoric.
                                                                                                 HISTORIC_DATE_HEADER);
            LastSearchesRadGridView.Columns["LastSearchesHourHeader"].Header = Resx.GetLabel(ResxHistoric.
                                                                                                 HISTORIC_HOUR_HEADER);
            LastSearchesRadGridView.Columns["LastSearchesOrganizationHeader"].Header =
                Resx.GetLabel(ResxHistoric.HISTORIC_ORGANIZATION_HEADER);
            LastSearchesRadGridView.Columns["LastSearchesFolderTypeHeader"].Header =
                Resx.GetLabel(ResxHistoric.HISTORIC_FOLDERTYPE_HEADER);
            LastSearchesRadGridView.Columns["LastSearchesNbResultsHeader"].Header = Resx.GetLabel(
                ResxHistoric.HISTORIC_NBRESULTS_HEADER);
            LastSearchesRadGridView.Columns["LastSearchesIndexHeader"].Header = Resx.GetLabel(ResxHistoric.
                                                                                                  HISTORIC_INDEX_HEADER);

            SavedSearchesTabItem.Header = Resx.GetLabel(ResxHistoric.HISTORIC_SAVED_SEARCHES);
            SavedSearchesDisplayButton.Content = Resx.GetLabel(ResxHistoric.HISTORIC_DISPLAY);
            SavedSearchesDeleteButton.Content = Resx.GetLabel(ResxHistoric.HISTORIC_DELETE);
            SavedSearchesRadGridView.Columns["SavedSearchesDateHeader"].Header = Resx.GetLabel(
                ResxHistoric.
                    HISTORIC_DATE_HEADER);
            SavedSearchesRadGridView.Columns["SavedSearchesHourHeader"].Header = Resx.GetLabel(
                ResxHistoric.
                    HISTORIC_HOUR_HEADER);
            SavedSearchesRadGridView.Columns["SavedSearchesOrganizationHeader"].Header =
                Resx.GetLabel(ResxHistoric.HISTORIC_ORGANIZATION_HEADER);
            SavedSearchesRadGridView.Columns["SavedSearchesFolderTypeHeader"].Header =
                Resx.GetLabel(ResxHistoric.HISTORIC_FOLDERTYPE_HEADER);
            SavedSearchesRadGridView.Columns["SavedSearchesNbResultsHeader"].Header =
                Resx.GetLabel(ResxHistoric.HISTORIC_NBRESULTS_HEADER);
            SavedSearchesRadGridView.Columns["SavedSearchesIndexHeader"].Header = Resx.GetLabel(
                ResxHistoric.
                    HISTORIC_INDEX_HEADER);
        }

        /// <summary>
        ///   Called when [cell double click].
        /// </summary>
        /// <param name = "sender">The sender.</param>
        /// <param name = "args">The <see cref = "Telerik.Windows.RadRoutedEventArgs" /> instance containing the event data.</param>
        private void OnCellDoubleClick_Consultation(object sender, RadRoutedEventArgs args)
        {
            OpenSelectedItem(HistoricAction.Consultation);
        }

        /// <summary>
        ///   Called when [cell double click_ search].
        /// </summary>
        /// <param name = "sender">The sender.</param>
        /// <param name = "args">The <see cref = "Telerik.Windows.RadRoutedEventArgs" /> instance containing the event data.</param>
        private void OnCellDoubleClick_Search(object sender, RadRoutedEventArgs args)
        {
            OpenSelectedItem(HistoricAction.Search);
        }

        /// <summary>
        ///   Called when [cell double click_ saved search].
        /// </summary>
        /// <param name = "sender">The sender.</param>
        /// <param name = "args">The <see cref = "Telerik.Windows.RadRoutedEventArgs" /> instance containing the event data.</param>
        private void OnCellDoubleClick_SavedSearch(object sender, RadRoutedEventArgs args)
        {
            OpenSelectedItem(HistoricAction.SavedSearch);
        }

        private void OnCellDoubleClick_Import(object sender, RadRoutedEventArgs args)
        {
            OpenSelectedItem(HistoricAction.Import);
        }

        /// <summary>
        ///   Handles the Click event of the Open control.
        /// </summary>
        /// <param name = "sender">The source of the event.</param>
        /// <param name = "e">The <see cref = "System.Windows.RoutedEventArgs" /> instance containing the event data.</param>
        private void Open_Click(object sender, RoutedEventArgs e)
        {
            Button b = sender as Button;
            if (b == LastConsultationsDisplayButton)
            {
                OpenSelectedItem(HistoricAction.Consultation);
            }
            else if (b == LastSearchesDisplayButton)
            {
                OpenSelectedItem(HistoricAction.Search);
            }
            else if (b == SavedSearchesDisplayButton)
            {
                OpenSelectedItem(HistoricAction.SavedSearch);
            }
            else if (b == LastIndexationsDisplayButton)
            {
                OpenSelectedItem(HistoricAction.Import);
            }
        }

        /// <summary>
        ///   Opens the selected item.
        /// </summary>
        /// <param name = "searchHistoricAction">The search historic action.</param>
        public void OpenSelectedItem(HistoricAction searchHistoricAction)
        {
            HistoricInformation historicInformationSource = null;

            switch (searchHistoricAction)
            {
                case HistoricAction.Consultation:
                    historicInformationSource = SelectedLastConsultations;
                    break;
                case HistoricAction.Search:
                    historicInformationSource = SelectedLastSearches;
                    break;
                case HistoricAction.SavedSearch:
                    historicInformationSource = SelectedSavedSearches;
                    if (historicInformationSource == null
                        && SavedSearchesRadGridView.SelectedItems != null)
                    {
                        historicInformationSource =
                            new List<HistoricInformation>(
                                SavedSearchesRadGridView.SelectedItems.Cast<HistoricInformation>()).FirstOrDefault();
                    }

                    break;
                case HistoricAction.Import:
                    historicInformationSource = SelectedLastIndexations;
                    break;
            }

            if (historicInformationSource != null)
            {
                switch (searchHistoricAction)
                {
                    case HistoricAction.Consultation:
                        NavigationHelper.Instance.GetFolderLink(historicInformationSource.OrganizationId,
                                                                historicInformationSource.FolderTypeId,
                                                                historicInformationSource.FolderId,
                                                                historicInformationSource.FolderIdDoc,
                                                                true);
                        break;
                    case HistoricAction.Import:
                        NavigationHelper.Instance.GetImportLink(historicInformationSource.OrganizationId,
                                                                historicInformationSource.FolderTypeId,
                                                                historicInformationSource.Indexes.ToList(),
                                                                true);
                        break;
                    case HistoricAction.SavedSearch:
                    case HistoricAction.Search:
                        NavigationHelper.Instance.GetSearcResultLink(historicInformationSource.OrganizationId,
                                                                     historicInformationSource.FolderTypeId,
                                                                     historicInformationSource.Indexes.ToList(),
                                                                     true);
                        break;
                }
            }
        }

        /// <summary>
        ///   Handles the Click event of the Delete control.
        /// </summary>
        /// <param name = "sender">The source of the event.</param>
        /// <param name = "e">The <see cref = "System.Windows.RoutedEventArgs" /> instance containing the event data.</param>
        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxChildWindow L_oMessageToValidate = new MessageBoxChildWindow(String.Empty,
                                                                                   Resx.GetLabel(
                                                                                       ResxHistoric.
                                                                                           HISTORIC_MSG_DELETE_SEARCH_SAVE),
                                                                                   MessageBoxButtons.OkCancel,
                                                                                   MessageBoxIcon.Warning);
            L_oMessageToValidate.Show();
            L_oMessageToValidate.Closed += (s, ev) =>
                                               {
                                                   if (L_oMessageToValidate.Result
                                                       == MessageBoxResult.OK)
                                                   {
                                                       DeleteSelectedSavedSearch();
                                                   }
                                               };
        }

        /// <summary>
        ///   Called when [property changed].
        /// </summary>
        /// <param name = "propertyName">Name of the property.</param>
        public void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        private void historicDashboardLoaded(object sender, RoutedEventArgs e)
        {
            LoadHistoric();
        }

        #region HistoricAction enum

        public enum HistoricAction
        {
            Consultation,
            Search,
            SavedSearch,
            Import
        }

        #endregion
    }
}